import fetch from 'dva/fetch';
import { message } from 'antd';

import { UrlConfig } from '../services/fetch';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}


// function deepClone(obj) {
//   let _obj = JSON.stringify(obj),
//     objClone = JSON.parse(_obj);
//   return objClone
// }

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  let token = window.localStorage.getItem('token');
  let site_id = window.localStorage.getItem('site_id');
  if(!options){
    options = {
      method: 'get',
      headers: { 'Content-Type': 'application/json; charset=utf-8' }
    };
  }
  options.headers.token = token;
  options.headers.site_id = site_id;

  // if (options) {  //post
  //   let body = JSON.parse(options.body);
  //   body.token = token;
  //   body.site_id = site_id;
  //   options.body = JSON.stringify(body);
  // } else {      //get
  //   let str = '?'
  //   if (url.indexOf('?') > -1) {
  //     str = '&';
  //   }
  //   url = `${url}${str}token=${token}&site_id=${site_id}`;
  // }
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
    //   debugger;
      if(data.code == 501){
        message.destroy();
        message.warning(data.msg + "：登陆已过期，请重新登陆！");
        setTimeout(() => { 
          if(window.self != window.top){
            window.top.location.href = UrlConfig + "/#/login";
          }else{
            window.location.href = UrlConfig + "/#/login";
          }
        }, 2000);
        return;
      }else{
        return { data }
      }
    })
    .catch(err => ({ err }));
}


export function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
/**
 * 上传图片前置钩子
 * @param {文件对象} file
 */
export function beforeImgUpload(file, status) {
  if (status) {
    message.error('文件正在上传中.');
    return false;
  }
  let flag = true;
  const isJPEG = file.type === 'image/jpeg';
  const isJPG = file.type === 'image/jpg';
  const isPNG = file.type === 'image/png';
  if (!isJPG && !isPNG && !isJPEG) {
    message.error('只能上传jpg、jpeg、png类型的图片');
    flag = false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('只能上传2M 以内的图片！');
    flag = false;
  }
  return flag
}

/**
 * 上传视频前置钩子
 * @param {文件对象} file
 */
export function beforeVideoUpload(file, status) {
  if (status) {
    message.error('文件正在上传中.');
    return false;
  }
  let flag = true;
  const isMP4 = file.type === 'video/mp4';
  if (!isMP4) {
    message.error('只能上传MP4类型的视频');
    flag = false;
  }
  const isLt2M = file.size / 1024 / 1024 < 50;
  if (!isLt2M) {
    message.error('只能上传50M 以内的视频！');
    flag = false;
  }
  return flag
}


export function deepClone(data) {
  var obj = {};
  var originQueue = [data];
  var copyQueue = [obj];
  //以下两个队列用来保存复制过程中访问过的对象，以此来避免对象环的问题（对象的某个属性值是对象本身）
  var visitQueue = [];
  var copyVisitQueue = [];
  while (originQueue.length > 0) {
    var _data = originQueue.shift();
    var _obj = copyQueue.shift();
    visitQueue.push(_data);
    copyVisitQueue.push(_obj);
    for (var key in _data) {
      var _value = _data[key]
      if (typeof _value !== 'object') {
        _obj[key] = _value;
      } else {
        //使用indexOf可以发现数组中是否存在相同的对象(实现indexOf的难点就在于对象比较)
        var index = visitQueue.indexOf(_value);
        if (index >= 0) {
          // 出现环的情况不需要再取出遍历
          _obj[key] = copyVisitQueue[index];
        } else {
          originQueue.push(_value);
          _obj[key] = {};
          copyQueue.push(_obj[key]);
        }
      }
    }
  }
  return obj;
}

export function checkPrivilege(privilege, loginModel) {
  if (loginModel.privilege_list && loginModel.privilege_list.indexOf(privilege) > -1) {
    return true;
  } else {
    return false;
  }
}


export const noImg = "";
